package cn.keyvalue.ccf.common.object;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import cn.keyvalue.ccf.common.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;

@Service
/**
 * 简易计数器
 * @author wangxinning
 *
 */
public class SimpleCounter {

	private static Logger logger = Logger.getLogger(SimpleCounter.class);
	
	private ConcurrentMap<String,AtomicInteger> counterMap = new ConcurrentHashMap<String,AtomicInteger>();
	
	public int incrementAndGet( String key )
	{
		initOneCounter( key );
		AtomicInteger counter = counterMap.get(key);
		return counter.incrementAndGet();
	}
	
	public int getValue( String key )
	{
		initOneCounter( key );
		AtomicInteger counter = counterMap.get(key);
		return counter.get();
	}
	
	public void clearCounter( String key )
	{
		counterMap.remove(key);
		initOneCounter( key );
	}
	
	public void clearCounter()
	{
		counterMap.clear();
	}
	
	public List<Map<String,Object>> getContentList()
	{
		List<Map<String,Object>> retList = new ArrayList<Map<String,Object>>();
		
		if(!counterMap.isEmpty())
		{
			Iterator<String> ite = counterMap.keySet().iterator();
			while( ite.hasNext() )
			{
				String key = ite.next();
				Integer value = counterMap.get(key).intValue();
				
				Map<String,Object> tempMap = new HashMap<String,Object>();
				tempMap.put("key",key);
				tempMap.put("value",value);
				
				retList.add(tempMap);
			}
			
			return retList;
		}
		
		return null;
	}
	
	private void initOneCounter(String key)
	{
		AtomicInteger counter = counterMap.get(key);
		if( counter == null )
		{
			counter = new AtomicInteger(0);
			counterMap.put(key, counter);			
		}
	}	
	
	/**
	 * 定时任务，打印当前计数器状态并清零
	 * 每小时59：59秒打印并清空
	 */
	@Scheduled(cron="59 59 * * * ?")
	public void printLogAndClear()
	{
		logger.info(StringUtils.repeat("*", 5));
		List<Map<String,Object>> plist = this.getContentList();
		
		if( !ObjectUtils.isEmptyList(plist) )
		{
			for( Map<String,Object> map:plist )
			{
				logger.info(map.get("key") + ":" + map.get("value"));				
			}
		}
		
		this.clearCounter();
	}
}
